package com.test.rabbitmq.routingtest;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-05-24 10:33
 */
public class EmitLogDirect {
    private static final String EXCHANGE_NAME = "direct_logs";
    private static final Logger LOGGER = LoggerFactory.getLogger(EmitLogDirect.class);
    private static boolean flag = true;

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 创建一个direct类型的exchange
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            while (flag) {
                String[] severities = {"info", "warning", "error"};
                Random random = new Random();
                String severity = severities[random.nextInt(3)];
                String message = new StringBuilder("[").append(severity).append("]").append("test log").toString();

                channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes("UTF-8"));
                LOGGER.info(" [x] Sent '" + severity + "':'" + message + "'");
                TimeUnit.SECONDS.sleep(1);
            }

        }
    }
}
